package com.hefan.api.service;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.cat.common.constant.RedisKeyConstant;
import com.cat.common.util.GuuidUtil;
import com.cat.tiger.service.JedisService;
import com.hefan.api.bean.LoginTokenVo;
import com.hefan.user.bean.LoginToken;
import com.hefan.user.itf.LoginTokenService;
import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Created by lxw on 2016/9/28.
 */
@Component
public class LoginTokenLocalService {

    @Resource
    private JedisService jedisService;
    
    @Reference
    private LoginTokenService loginTokenService;

    private Logger logger = LoggerFactory.getLogger(LoginTokenLocalService.class);

    /**
     * 向redis中保存登陆token和用户信息
     * @param loginTokenVo
     * @return
     */
    public String loginTokenCreater(LoginTokenVo loginTokenVo) throws Exception{
        try {
            loginTokenVo.setToken(GuuidUtil.getUuid());
            String key = String.format(RedisKeyConstant.LONG_TOKEN_KEY,loginTokenVo.getToken());
            logger.info("key==="+key);
            String resStr = jedisService.setexStr(key,JSON.toJSONString(loginTokenVo),30*24*60*60);
            logger.info("resStr==="+resStr);
            if(StringUtils.isNotBlank(resStr)) {
                return loginTokenVo.getToken();
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("error==loginTokenCreater");
            throw new RuntimeException(e);
        }
        return null;
    }

    /**
     * 由redis中获取登录token信息
     * @param token
     * @return
     */
    public LoginTokenVo getTokenFromRedis(String token) {
        String key = String.format(RedisKeyConstant.LONG_TOKEN_KEY,token);
        try {
            String jsonStr = jedisService.getStr(key);
            if(StringUtils.isBlank(jsonStr)) {
                return null;
            } else {
                return JSON.parseObject(jsonStr, LoginTokenVo.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
	/**
	 * 登录push token记录
	 * 
	 * @param loginToken
	 * @return
	 */
    @Async
	public void saveLoginToken(LoginToken loginToken) {
		loginTokenService.saveLoginToken(loginToken);
	}
}
